package com.sunmouse.toolkit.fragment.custom;


import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.sunmouse.toollib.utils.ToastUtils;
import com.sunmouse.toolkit.R;
import com.sunmouse.toolkit.constant.Config;
import com.sunmouse.toolkit.fragment.BaseFragment;
import com.sunmouse.toolkit.widget.progress.LoadBar;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class LoadBarFragment extends BaseFragment {


    @BindView(R.id.m_lb)
    LoadBar mLb;
    Unbinder unbinder;
    @BindView(R.id.start_btn)
    Button startBtn;
    @BindView(R.id.end_btn)
    Button endBtn;

    private Timer mTimer;
    private int progress;
    private int max;


    public LoadBarFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_load_bar, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void init() {
        this.startBtn.setOnClickListener(this);
        this.endBtn.setOnClickListener(this);
        this.max = 10;
        this.mLb.setMax(max);
        this.mTimer = new Timer();

        TextView tv;

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == startBtn) {
            progress = 0;
            mTimer.schedule(new ProgressTask(), 0, 1000);
            return;
        }
        if (v == endBtn) {
            mTimer.cancel();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }


    @Override
    public void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        if (msg.what==Config.Status.SUCCESS){
            ToastUtils.simpleToast(getActivity(), "finish");
        }
    }

    /**
     * progress task
     */
    class ProgressTask extends TimerTask {

        @Override
        public void run() {
            if (progress > max) {
                mHandler.sendEmptyMessage(Config.Status.SUCCESS);
                return;
            }
            mLb.setProgress(progress++);
        }
    }
}
